import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/sale_in_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/bean/bean_supervisor_visit.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/widget/supervisor_visit_header.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/widget/supervisor_visit_listitem_content.dart';

/*上周陪访列表*/

@ARoute(url: SaleInWidgetRoute.SALE_IN_SUPERVISOR_LASTWEEK_VISIT)
class SupervisorLastWeekVisit extends CommonPageWithTrack {
  SupervisorLastWeekVisit(BoostRouteOption option) : super();

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("收房-主管陪访-上周陪访", null);
  }


  @override
  void onInitState(CommonPageBloc pageBloc) {
    Map<String, dynamic> paramsMap = Map();
    paramsMap["page"] = 1;
    paramsMap["page_num"] = 10;
    paramsMap["week"] = "last";
    pageBloc.pageHttpGet(
        path: SaleInApi.supervisorVisitList,
        queryMap: paramsMap,
        widgetBuilderByData: (dynamic data) {
          BeanSupervisorVisit visitBean =
              BeanSupervisorVisit.fromJson(data) ?? BeanSupervisorVisit();
          return SupervisorLastWeekVisitWidget(visitBean, paramsMap, pageBloc);
        });
  }
}

class SupervisorLastWeekVisitWidget extends StatefulWidget {
  final Map<String, dynamic> paramsMap;
  final BeanSupervisorVisit visitBean;
  final CommonPageBloc pageBloc;

  SupervisorLastWeekVisitWidget(this.visitBean, this.paramsMap, this.pageBloc);

  @override
  SupervisorLastWeekVisitState createState() {
    return SupervisorLastWeekVisitState(
        this.visitBean, this.paramsMap, this.pageBloc);
  }
}

class SupervisorLastWeekVisitState extends State<SupervisorLastWeekVisitWidget>
    with SingleTickerProviderStateMixin {
  Map<String, dynamic> paramsMap;
  CommonPageBloc pageBloc;
  BeanSupervisorVisit visitBean;
  DkEasyRefreshController easyRefreshController;
  SupervisorLastWeekVisitState(this.visitBean, this.paramsMap, this.pageBloc);
  int pageIndex = 1;
  @override
  void initState() {
    super.initState();
    easyRefreshController = DkEasyRefreshController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DkAppBar(DKAppBarParams.withBackMenu(
        context,
        [],
        titleContent: "上周任务",
      )),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: getAllItems(),
        ),
      ),
    );
  }

  Future<void> refreshPage() async {
    this.pageIndex = 1;
    paramsMap['page'] = this.pageIndex;
    pageBloc.dataHttpGet(
        path: SaleInApi.supervisorVisitList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          BeanSupervisorVisit visitResult = BeanSupervisorVisit.fromJson(data);
          visitBean = visitResult;
          setState(() {
            easyRefreshController.finishRefresh(success: true);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishRefresh(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishRefresh(success: false);
        });
  }

  Future<void> loadMore() async {
    paramsMap['page'] = (++this.pageIndex);
    pageBloc.dataHttpGet(
        path: SaleInApi.supervisorVisitList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          BeanSupervisorVisit visitResult = BeanSupervisorVisit.fromJson(data);
          visitBean.data.addAll(visitResult.data);
          setState(() {
            easyRefreshController.finishLoad(
                success: true,
                noMore: this.pageIndex >= this.visitBean.lastPage);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishLoad(success: false);
        });
  }

  List<Widget> getAllItems() {
    bool noMore = this.pageIndex >= this.visitBean.lastPage;
    List<Widget> datas = List<Widget>();
    datas.add(VisitHeaderWidget(HeaderOption.hasNoButton(visitBean)));
    datas.add(Expanded(
        flex: 1,
        child: Container(
          color: Colors.white,
          child: DkRefreshListWidget.custom(
              controller: easyRefreshController,
              onLoad: noMore ? null : this.loadMore,
              onRefresh: this.refreshPage,
              emptyWidget: this.visitBean.data.length == 0
                  ? LogicPage(PortalConfig.smallEmptyPageParam)
                  : null,
              slivers: <Widget>[
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      DataListBean dataListBean = visitBean.data[index];
                      return getListItemCell(dataListBean);
                    },
                    childCount: this.visitBean.data.length,
                  ),
                ),
              ]),
        )));
    return datas;
  }
}

Widget getListItemCell(DataListBean dataListBean) {
  dataListBean.status ??= "";
  dataListBean.executeType ??= " ";
  String listId = "任务号: " + dataListBean.id.toString();
  String name = "销售: " + (dataListBean?.dealerName ?? "");
  String date = "陪访时间: " + (dataListBean.visitAt ?? "");
  double topPadding = stringBlank(dataListBean.status) ? 0 : 4;
  double leftPadding = stringBlank(dataListBean.status) ? 0 : 8;
  return Container(
    margin: EdgeInsets.only(bottom: 10),
    color: Colors.white,
    child: InkWell(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          SupervisorListItemContent(
              SupervisorListItemParams(listId, name, date)),
          Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(top: 13),
                alignment: Alignment.centerRight,
                margin: EdgeInsets.only(right: 15),
                child: Container(
                  padding: EdgeInsets.fromLTRB(
                      leftPadding, topPadding, leftPadding, topPadding),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(14),
                      topRight: Radius.circular(14),
                      bottomRight: Radius.circular(14),
                    ),
                    color: Color(int.parse(
                        "0xff" + (dataListBean.statusColor ?? "0000"))),
                  ),
                  child: Text(
                    dataListBean.status,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
              Container(
                alignment: Alignment.centerRight,
                margin: EdgeInsets.only(right: 15, top: 6, bottom: 20),
                child: Container(
                  child: Text(
                    dataListBean.executeType,
                    style: TextStyle(
                      color: Color(0xff666666),
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
      onTap: () {
        RouteUtil.goPage(dataListBean.url);
      },
    ),
  );
}
